package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.GoodsTypeDao;
import com.atguigu.jxc.entity.GoodsType;
import com.atguigu.jxc.service.GoodsTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GoodsTypeServiceImpl implements GoodsTypeService {

    @Autowired
    private GoodsTypeDao goodsTypeDao;

    @Override
    public List<Map> getCatalog() {
        List<GoodsType> goodsTypes = goodsTypeDao.getCatalog();
        List<Map> maps = new ArrayList<>();

        Map<String, Object> map = new HashMap<>();
        for (GoodsType goodsType : goodsTypes) {
            if (goodsType.getPId().equals(-1)) {
                map = this.getMap(goodsType, goodsTypes);
                maps.add(map);
            }
        }
        return maps;
    }

    @Transactional
    @Override
    public void save(String goodsTypeName, Integer pId) {
        goodsTypeDao.save(goodsTypeName,pId);
        goodsTypeDao.updateStatus(pId);
    }

    @Override
    public void delete(Integer goodsTypeId) {
        goodsTypeDao.delete(goodsTypeId);
    }

    private Map getMap(GoodsType goodsType, List<GoodsType> goodsTypes) {
        Map map = this.getMap(goodsType);
        Integer goodsTypeId = goodsType.getGoodsTypeId();
        List<Map> childrenList = new ArrayList<>();
        for (GoodsType childrenGoodsType : goodsTypes) {
            if (goodsTypeId.equals(childrenGoodsType.getPId())) {
                if (childrenGoodsType.getGoodsTypeState() == 1) {
                    Map map1 = this.getMap(childrenGoodsType, goodsTypes);
                    childrenList.add(map1);
                } else {
                    Map map1 = this.getMap(childrenGoodsType);
                    childrenList.add(map1);
                }
            }
        }
        map.put("children", childrenList);
        return map;
    }

    private Map getMap(GoodsType goodsType) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", goodsType.getGoodsTypeId());
        map.put("text", goodsType.getGoodsTypeName());
        map.put("state", goodsType.getGoodsTypeState() == 1 ? "closed" : "open");
        map.put("iconCls", "goods-type");
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("state", goodsType.getGoodsTypeState());
        map.put("attributes", hashMap);
        return map;
    }

}
